// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.PurchaseOrderProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.PurchaseOrderProductMapper;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductItemVo;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductItemVoPages;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductSearchParamPo;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductVo;
import com.fowo.api.service.PurchaseOrderProductService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.AccessManager;
import com.fowo.api.sys.component.FieldPermissionGroupManager;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.user.model.JwtUserInfo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 采购订单子表 服务实现类
 * @author 蜂窝蜜造平台 配置人：王阳阳，尹建栋
 */
@Service
@Slf4j
@DataObjectType(PurchaseOrderProduct.class)
@DS("ds24")
public class PurchaseOrderProductServiceImpl
  extends ServiceImpl<PurchaseOrderProductMapper, PurchaseOrderProduct>
  implements PurchaseOrderProductService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("productIdName", "p.`name`");
      put("sidShopName", "si.`shop_name`");
      put("fnskuFnsku", "lf.`fnsku`");
      put("purchaseOrderIdPurchaseOrderCode", "po.`purchase_order_code`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected PurchaseOrderProductService self;

  @Resource
  protected FieldPermissionGroupManager fieldPermissionGroupManager;

  @Resource
  protected AccessManager accessManager;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建采购订单子表
   * @param model 采购订单子表
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(PurchaseOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    // 字段权限组过滤
    fieldPermissionGroupManager.filterFields(
      model,
      "priceAuthority",
      "unitPrice",
      "costPrice",
      "mainUnitPrice",
      "gramWeight",
      "laborCosts",
      "accessoriesPrice",
      "amount",
      "totalPrice"
    );
    PurchaseOrderProduct entity = new PurchaseOrderProduct();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getMaterialloss() == null) {
      entity.setMaterialloss(new BigDecimal("1.2"));
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("采购订单子表保存失败");
  }

  /**
   * 批量更新 采购订单 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByPurchaseOrderId(
    Long purchaseOrderId,
    List<PurchaseOrderProductItemVo> list
  ) throws Exception {
    for (PurchaseOrderProductItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      PurchaseOrderProduct item = new PurchaseOrderProduct();
      BeanUtils.copyProperties(itemVo, item);
      if (item.getPurchaseOrderId() == null) {
        item.setId(null);
        item.setPurchaseOrderId(purchaseOrderId);
      }
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 返回 采购订单 下属多级分页
   */
  @Override
  public Map<String, Page<PurchaseOrderProductItemVoPages>> pagesByPurchaseOrderId(
    PurchaseOrderProductSearchParamPo search
  ) {
    search.setDisableDataPremissions(true);
    List<PurchaseOrderProductItemVoPages> listMap =
      baseMapper.selectPagesByPurchaseOrderId(search);
    Map<Long, List<PurchaseOrderProductItemVoPages>> pageMap = listMap
      .stream()
      .collect(
        Collectors.groupingBy(
          PurchaseOrderProductItemVoPages::getPurchaseOrderId
        )
      );
    Map<String, Page<PurchaseOrderProductItemVoPages>> result = new HashMap<>();
    for (Map.Entry<Long, List<PurchaseOrderProductItemVoPages>> listEntry : pageMap.entrySet()) {
      Page<PurchaseOrderProductItemVoPages> page = new Page<>(
        1,
        search.getPageSize(),
        listEntry.getValue().get(0).getPartRows()
      );
      page.setRecords(listEntry.getValue());
      result.put(listEntry.getKey().toString(), page);
    }
    return result;
  }

  /**
   * 更新采购订单子表
   * @param model 采购订单子表
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(PurchaseOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PurchaseOrderProduct entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("采购订单子表不存在");
    }
    // 字段权限组过滤
    fieldPermissionGroupManager.filterFields(
      model,
      "priceAuthority",
      "unitPrice",
      "costPrice",
      "mainUnitPrice",
      "gramWeight",
      "laborCosts",
      "accessoriesPrice",
      "amount",
      "totalPrice"
    );
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "picUrl",
      "businessIdent",
      "model",
      "totalPrice",
      "quantityReceived",
      "quantityReceive",
      "quantityReturn",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "crossQty",
      "localShopInventory",
      "otherShopInventory",
      "publicInventory",
      "lxPrice",
      "lxTotalPrice"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新采购订单子表（带空值）
   * @param model 采购订单子表
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(PurchaseOrderProductVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    PurchaseOrderProduct entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("采购订单子表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    // 需要 priceAuthority 权限才能更新 unitPrice,costPrice,mainUnitPrice,gramWeight,laborCosts,accessoriesPrice,amount,totalPrice
    boolean authorityPriceAuthority = accessManager.canAccess("priceAuthority");
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(PurchaseOrderProduct::getProductId, model.getProductId())
      .set(PurchaseOrderProduct::getSku, model.getSku())
      .set(PurchaseOrderProduct::getSid, model.getSid())
      .set(PurchaseOrderProduct::getFnsku, model.getFnsku())
      .set(PurchaseOrderProduct::getApplicationNum, model.getApplicationNum())
      .set(PurchaseOrderProduct::getTaxPrice, model.getTaxPrice())
      .set(
        PurchaseOrderProduct::getSupplierQuotation,
        model.getSupplierQuotation()
      )
      .set(
        authorityPriceAuthority,
        PurchaseOrderProduct::getUnitPrice,
        model.getUnitPrice()
      )
      .set(
        authorityPriceAuthority,
        PurchaseOrderProduct::getCostPrice,
        model.getCostPrice()
      )
      .set(
        authorityPriceAuthority,
        PurchaseOrderProduct::getMainUnitPrice,
        model.getMainUnitPrice()
      )
      .set(
        authorityPriceAuthority,
        PurchaseOrderProduct::getGramWeight,
        model.getGramWeight()
      )
      .set(
        authorityPriceAuthority,
        PurchaseOrderProduct::getLaborCosts,
        model.getLaborCosts()
      )
      .set(
        authorityPriceAuthority,
        PurchaseOrderProduct::getAccessoriesPrice,
        model.getAccessoriesPrice()
      )
      .set(PurchaseOrderProduct::getMaterialloss, model.getMaterialloss())
      .set(PurchaseOrderProduct::getMaterialpack, model.getMaterialpack())
      .set(PurchaseOrderProduct::getErpprice, model.getErpprice())
      .set(
        PurchaseOrderProduct::getExpectArriveTime,
        model.getExpectArriveTime()
      )
      .set(PurchaseOrderProduct::getLastUpdateTime, model.getLastUpdateTime())
      .set(PurchaseOrderProduct::getLastUpdateUser, model.getLastUpdateUser())
      .set(PurchaseOrderProduct::getArrivalDate, model.getArrivalDate())
      .set(PurchaseOrderProduct::getPurchaseOrderId, model.getPurchaseOrderId())
      .set(PurchaseOrderProduct::getRemarks, model.getRemarks())
      .set(
        PurchaseOrderProduct::getThreeSalesVolume,
        model.getThreeSalesVolume()
      )
      .set(
        PurchaseOrderProduct::getSevenSalesVolume,
        model.getSevenSalesVolume()
      )
      .set(
        PurchaseOrderProduct::getThirtySalesVolume,
        model.getThirtySalesVolume()
      )
      .set(PurchaseOrderProduct::getSameSales, model.getSameSales())
      .set(
        PurchaseOrderProduct::getReceivedGoodsValues,
        model.getReceivedGoodsValues()
      )
      .set(PurchaseOrderProduct::getReturnMoney, model.getReturnMoney())
      .set(PurchaseOrderProduct::getPayTime, model.getPayTime())
      .eq(PurchaseOrderProduct::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(
    PurchaseOrderProductSearchParamPo search
  ) {
    return false;
  }

  /**
   * 删除采购订单子表
   * @param id 采购订单子表的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除采购订单子表
   * @param ids 采购订单子表的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过需求部门查询采购订单子表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByApplicationDep(String applicationDep) {
    return this.baseMapper.getIdByApplicationDep(applicationDep);
  }

  /**
   * 通过需求部门查询采购订单子表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByApplicationDep(List<String> list) {
    return this.baseMapper.getIdsByApplicationDep(list);
  }

  /**
   * 通过采购订单子表主键查询需求部门
   */
  @Override
  public String getApplicationDepById(Long id) {
    return this.baseMapper.getApplicationDepById(id);
  }

  /**
   * 通过采购订单子表主键查询需求部门列表
   */
  @Override
  public List<String> getApplicationDepByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getApplicationDepByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("applicationDep")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 采购订单子表的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public PurchaseOrderProductVo getVoById(Long id) throws Exception {
    PurchaseOrderProductVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    // 字段权限组过滤
    fieldPermissionGroupManager.filterFields(
      vo,
      "priceAuthority",
      "unitPrice",
      "costPrice",
      "mainUnitPrice",
      "gramWeight",
      "laborCosts",
      "accessoriesPrice",
      "amount",
      "totalPrice"
    );
    return vo;
  }

  /**
   * 分页查询采购订单子表
   * @param search 查询条件
   * @return 采购订单子表分页查询结果
   */
  @Override
  public Page<PurchaseOrderProductItemVo> pageSearch(
    PurchaseOrderProductSearchParamPo search
  ) {
    Page<PurchaseOrderProductItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    // 字段权限组过滤
    fieldPermissionGroupManager.filterItemFields(
      page.getRecords(),
      "priceAuthority",
      "unitPrice",
      "costPrice",
      "mainUnitPrice",
      "gramWeight",
      "laborCosts",
      "accessoriesPrice",
      "amount",
      "totalPrice"
    );
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(PurchaseOrderProductItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 采购订单子表快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'PurchaseOrderProductOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<PurchaseOrderProductItemVo>> searchOptions(
    PurchaseOrderProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询采购订单子表
   * @param search 查询条件
   * @return 采购订单子表列表查询结果
   */
  @Override
  public List<PurchaseOrderProductItemVo> search(
    PurchaseOrderProductSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询采购订单子表最后更新时间
   * @param search 查询条件
   * @return 采购订单子表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(PurchaseOrderProductSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
